
import { queryExpertDetailById, updateMyExpertTalk } from "../../../../service/expert_service"
import { attentionAction } from "../../../../service/attention_service"
import { loginWxAction } from "../../../../service/config"
import { utils } from "../../../../sdk/imgColorUtil/imgColorUtil"
import debounce from "../../../../tools/debounce"
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    navBarTitle: "咨询专家",
    selectIndex: 0,
    isShowCommentPop: false,
    switchArr: [
      {
        title: "TA的楼盘"
      },
      {
        title: "TA的动态"
      }
    ],
    detailId: null,
    detailData: {},//详情
    houseList: [],
    dynList: [],
    isShare: false,
    menuTop: app.globalData.menuButton.top,
    menuHeight: app.globalData.menuButton.height,
    showNavTitle: false,
    showNavFirst: false,
    showNavTwo: false,
    isLoadImg: false,
    pageBackgroundColor: "linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(0, 0, 0, 1))",
    mainImgBgColors: [169, 169, 169],
    navBarTopBgColor: "rgba(169,169,169,0)",
    talkAbout: "该专家暂无简介",
    isMyDetail: false,
    checkRemarkText: "",
    showExpertBgPath: "",
    expertBgOnePath: "https://saas.img.ylyc.top/bg/expertfirstbg_icon.png",
    expertBgTwoPath: "https://saas.img.ylyc.top/bg/experttwobg_icon.png",
    expertBgThreePath: "https://saas.img.ylyc.top/bg/expertthree_icon.png",
    expertBgArr: [
      "https://saas.img.ylyc.top/bg/expertfirstbg_icon.png",
      "https://saas.img.ylyc.top/expert_bg.jpg",
      "https://saas.img.ylyc.top/bg/expertthree_icon.png",
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      detailId: options.id
    })
    if (options.isShare == 1) {
      this.setData({
        isShare: true
      })
      this.userWxLogin();
      return;
    }
    this.queryExpertDetailById();
    let number = Math.ceil(Math.random() * 3);
    let path = this.data.expertBgArr[number - 1];
    this.setData({
      showExpertBgPath: path,
    })
    this.downImgAction(path);
  },
  downImgAction(imgPath) {

    wx.downloadFile({
      url: imgPath,
      success: res => {

        this.getMainColor(res.tempFilePath)
      }
    })
  },
  getMainColor(imagePath) {
    let that = this;
    setTimeout(() => {
      const canvasId = "imgcanvas";
      utils.colors(imagePath, canvasId, {
        success: function (res) {
          console.log("dominant: " + res.dominant);
          console.log("secondary: " + res.secondary);
          console.log("palette: " + res.palette);

          const fontColor = utils.isLight(res.dominant) ? "#000000" : "#ffffff";
          const bgColor = utils.rgbToHex(res.dominant);
          const rgbArr = utils.isMyRgb(res.dominant);
          let resultStr = "linear-gradient(to bottom, rgba(" + rgbArr[0] + "," + rgbArr[1] + "," + rgbArr[2] + ", 0), rgba(" + rgbArr[0] + "," + rgbArr[1] + "," + rgbArr[2] + "," + 1 + "))"
          that.setData({
            pageBackgroundColor: resultStr,
            mainImgBgColors: rgbArr,
          })
          // console.log("JJLog:res=:" + resultStr);
          // console.log("JJLog:实际rgb:" + rgb);
          // console.log("JJLog:前景色是:" + fontColor);
          // console.log("JJLog:背景色是:" + bgColor);
        },
        width: 375,
        height: 280
      });
    }, 300)

  },
  //用户登陆授权等:
  userWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      if (res.code == 200) {
        this.queryExpertDetailById();
      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);
      wx.switchTab({
        url: '/pages/home/home',
      })
    })
  },
  //scroll滚动绑定
  scrollBindAction(e) {
    console.log("JJLog:滚动了:" + JSON.stringify(e));
    let arr = this.data.mainImgBgColors;
    let scrollTop = e.detail.scrollTop;
    if (scrollTop <= 80) {
      let str3 = "rgba(" + arr[0] + "," + arr[1] + "," + arr[2] + "," + 0 + ")"
      this.setData({
        showNavTitle: false,
        navBarTopBgColor: str3
      })
      return;
    }
    // if (scrollTop > 130) {
    //   let str1 = "rgba(" + arr[0] + "," + arr[1] + "," + arr[2] + "," + 0.5 + ")"
    //   this.setData({
    //     navBarTopBgColor: str1
    //   })
    // }
    if (scrollTop > 80 && scrollTop < 100) {
      let str2 = "rgba(" + arr[0] + "," + arr[1] + "," + arr[2] + "," + 0.5 + ")"
      this.setData({
        showNavTitle: false,
        navBarTopBgColor: str2
      })
      return;
    }
    if (scrollTop >= 100) {
      if (this.data.showNavTitle) {
        return;
      }
      let str2 = "rgba(" + arr[0] + "," + arr[1] + "," + arr[2] + "," + 1 + ")"
      this.setData({
        showNavTitle: true,
        navBarTopBgColor: str2
      })
    }


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
  },
  //查询置业顾问详情
  queryExpertDetailById() {
    wx.showLoading();
    queryExpertDetailById(this.data.detailId).then(res => {
      wx.hideLoading();
      console.log("JJLog:详情是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          detailData: res.data,
          houseList: res.data.houses || [],
          dynList: res.data.dyns,
        })
        if (res.data.talkAbout) {
          this.setData({
            talkAbout: res.data.talkAbout
          })
          // console.log("JJLog:djsjfhdsjfhj");
          if (app.globalData.userId == res.data.wxUserId) {

            this.setData({
              isMyDetail: true
            })
          }
        } else {
          if (app.globalData.userId == res.data.wxUserId) {
            this.setData({
              talkAbout: "编辑您的个人简介",
              isMyDetail: true
            })
          }
        }
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
      console.error("JJLog:queryExpertDetailById", err);
    })
  },

  //顶部切换
  switchAction(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      selectIndex: index
    })
  },


  //跳转至聊天
  pushToChatAction() {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    let item = this.data.detailData
    let chatData = {
      name: item.name,
      avatar: item.avatar,
      chatUserId: item.openId,
      conversationType: "C2C",
      houseNumber: "",
      houseName: "",
      expertId: item.id,
      expertPhone: item.phone || "",
      expertWeChat: item.wxChat || "",
    }
    app.globalData.chatData = chatData;
    wx.navigateTo({
      url: '/firstPackage/pages/msgModule/chatRoom/chatRoom',
    })
  },
  callPhoneAction() {
    wx.makePhoneCall({
      phoneNumber: this.data.detailData.phone,
      fail: err => {

      }
    })
  },
  //点赞操作:
  collectAction(e) {
    let { data, index } = e.detail;
    this.attentionAction(data, index);
  },
  //关注操作
  attentionAction(item, index) {
    let data = {
      collectType: 1,
      number: item.houseNumber
    }
    wx.showLoading();
    attentionAction(data).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        item.isCollect = !item.isCollect;
        //动态数组:
        let changeItem = 'houseList[' + index + '].isCollect';
        this.setData({
          [changeItem]: item.isCollect,
        })
        wx.showToast({
          title: item.isCollect ? "关注成功" : "取关成功",
          icon: "none"
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "操作失败",
        icon: "none"
      })
      console.error("JJLog:attentionAction", err);
    })
  },

  //回到首页
  backHomeAction() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  //复制微信号:
  copyWxChatAction(e) {
    let text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制微信号成功'
            })
          },
          fail: function (err) {
            wx.showToast({
              title: '复制失败',
              icon: "none"
            })
          }
        })
      }
    })
  },

  previewQrCodeAction(e) {
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: [url],
    })
  },
  backPopPage() {
    wx.navigateBack({
      delta: 0,
    })
  },
  backHomePage() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  //编辑我的个人简介
  editMyTalkAction() {
    if (this.data.isMyDetail) {
      this.setData({
        isShowCommentPop: true
      })
    }
  },
  hideCommentPop() {
    this.setData({
      isShowCommentPop: false
    })
  },
  //确定编辑
  checkRemarkSend(e) {
    console.log("JJLog:e:" + JSON.stringify(e));
    let remarkText = e.detail.comment;
    if (!remarkText) {
      wx.showToast({
        title: '请输入您的简介内容',
        icon: "none"
      })
      return;
    }
    this.setData({
      checkRemarkText: remarkText,
      isShowCommentPop: false
    })

    this.updateMyExpertTalk();
  },
  updateMyExpertTalk() {
    wx.showLoading();
    updateMyExpertTalk(this.data.checkRemarkText).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '编辑成功',
          icon: "success"
        })
        this.setData({
          talkAbout: this.data.checkRemarkText
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "操作失败",
        icon: "none"
      })
      console.error("JJLog:updateMyExpertTalk", err);
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.commonShareTitle,
      path: `/firstPackage/pages/expertModule/newExpertDetail/newExpertDetail?isShare=1&id=${this.data.detailId}`,
    }
  }
})